package com.example.communicate;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerHandler {
    private ServerSocket serverSocket;

    // 构造方法，初始化服务器Socket
    public ServerHandler(int port) throws IOException {
        this.serverSocket = new ServerSocket(port);
    }

    // 开始监听客户端连接
    public void start() {
        System.out.println("服务器启动，等待客户端连接...");
        while (true) {
            try {
                Socket clientSocket = serverSocket.accept();
                System.out.println("客户端连接: " + clientSocket.getInetAddress());
                // 处理客户端连接（此处可以使用线程池处理多个客户端）
                new Thread(new ClientProcessor(clientSocket)).start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 内部类，用于处理客户端请求
    private static class ClientProcessor implements Runnable {
        private Socket clientSocket;

        public ClientProcessor(Socket clientSocket) {
            this.clientSocket = clientSocket;
        }

        @Override
        public void run() {
            // 处理客户端请求逻辑
            try {
                byte[] buffer = new byte[1024];
                int length = clientSocket.getInputStream().read(buffer);
                String receivedData = new String(buffer, 0, length);
                System.out.println("接收到客户端数据: " + receivedData);
                // 回应客户端
                clientSocket.getOutputStream().write("已收到".getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    clientSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
